<template>
    <div id="app">
        <v-app id="inspire">
            <template v-slot:top>
                <v-toolbar flat color="white">
                    <v-toolbar-title>KubeEdge Application Management</v-toolbar-title>
                    <v-divider
                            class="mx-4"
                            inset
                            vertical
                    ></v-divider>
                    <v-spacer></v-spacer>
                </v-toolbar>
            </template>
            <template>
                <v-form>
                    <v-container>
                        <v-row>
                            <v-col
                                    cols="12"
                                    md="2"
                            >
                                <VueCtkDateTimePicker format='DD-MM-YYYY HH:mm' v-model="elasticsearch.starttime" />
                            </v-col>
                            <v-col
                                    cols="12"
                                    md="2"
                            >
                                <VueCtkDateTimePicker format='DD-MM-YYYY HH:mm' v-model="elasticsearch.endtime" />
                            </v-col>
                            <v-col
                                    cols="12"
                                    md="2"
                            >
                                <v-select
                                        :items="indexes"
                                        item-value="id"
                                        item-text="index_name"
                                        v-model="elasticsearch.selected_index"
                                ></v-select>
                            </v-col>
                            <v-col
                                    cols="12"
                                    md="2"
                            >
                                <v-text-field
                                        v-model="elasticsearch.keywords"
                                        label="Search Word"
                                        hint="keywords for search"
                                        required
                                ></v-text-field>
                            </v-col>
                            <v-col
                                    cols="12"
                                    md="3"
                            >
                                <v-select
                                        v-model="elasticsearch.search_fields"
                                        :items="header"
                                        label="Search Fields"
                                        hint="input comma delimiter fields,e.g 'a,b,c' "
                                        required
                                        multiple
                                ></v-select>
                            </v-col>
                            <v-col
                                    cols="12"
                                    md="1"
                            >
                                <v-btn color="cyan" class="ma-2 white--text" :loading=this.$store.state.isLoading  @click="getlogs()">Query</v-btn>
                            </v-col>
                        </v-row>

                        <v-row>
                            <v-col
                                    cols="12"
                                    md="12"
                            >
                                <div id="area-datetime">
                                    <apexchart type="area" height="350" ref="chart" :options="chartOptions" :series="series"></apexchart>
                                </div>
                            </v-col>
                        </v-row>
                        <v-row>

                        </v-row>
                    </v-container>
                </v-form>
                <v-data-table
                        :headers="header"
                        :items="logData"
                        :single-expand="singleExpand"
                        :expanded.sync="expanded"
                        :options.sync="options"
                        :loading="this.$store.state.isLoading"
                        item-key="_id"
                        show-expand
                        :server-items-length="totalNumberOfItems"
                        class="elevation-1"
                        no-data-text="No data found"
                >
                    <template v-slot:top>
                        <v-toolbar flat>
                            <v-toolbar-title>Log List</v-toolbar-title>
                            <v-spacer></v-spacer>
                            <v-switch
                                    v-model="singleExpand"
                                    label="Expandable"
                                    class="mt-2"
                            ></v-switch>
                        </v-toolbar>
                    </template>
                    <template v-slot:expanded-item="{ headers, item }">
                        <td :colspan="headers.length">
                            {{ item }}
                        </td>
                    </template>
                </v-data-table>
            </template>
        </v-app>
    </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import VueCtkDateTimePicker from 'vue-ctk-date-time-picker';
import 'vue-ctk-date-time-picker/dist/vue-ctk-date-time-picker.css';
import VueApexCharts from 'vue-apexcharts'

export default {
    component: {
        'VueCtkDateTimePicker': VueCtkDateTimePicker,
        'apexchart': VueApexCharts
    },
    data () {
        return {
            loading: true,
            options: {},
            page: 1,
            elasticsearch: {
                selected_index: 0,
                starttime: "",
                endtime: "",
                keywords: "",
                search_fields: "",
            },
            expanded: [],
            singleExpand: false,
        }
    },
    methods: {
        ...mapActions(
            'es', ['GetIndexList', 'GetLogs','GetHeader']),
        timestamp_convert: function (time) {
            var dateString = time,
                dateTimeParts = dateString.split(' '),
                timeParts = dateTimeParts[1].split(':'),
                dateParts = dateTimeParts[0].split('-'),
                date;
            date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
            return date.getTime()
        },
        getlogs: function () {
            let params = {}
            if (this.elasticsearch.starttime != "") {
                params.starttime = this.timestamp_convert(this.elasticsearch.starttime)
//                this.chartOptions.xaxis.min = params.starttime
            };
            if (this.elasticsearch.endtime != "") {
                params.endtime = this.timestamp_convert(this.elasticsearch.endtime)
            };
            if (this.options.page) {
                params.page = this.options.page
            };
            if (this.options.itemsPerPage) {
                params.itemsPerPage = this.options.itemsPerPage
            };
            if (this.options.sortBy != []) {
                params.sortBy = this.options.sortBy[0]
            };
            if (this.options.sortDesc != []) {
                params.sortDesc = this.options.sortDesc[0]
            };
            if (this.elasticsearch.search_fields) {
                params.search_fields = this.elasticsearch.search_fields.join(',')
            };
            if (this.elasticsearch.selected_index) {
                params.selected_index = this.elasticsearch.selected_index
            };
            if (this.elasticsearch.keywords) {
                params.keywords = this.elasticsearch.keywords
            };
            this.GetLogs(params)
            this.loading = false
        }
    },
    computed: {
        ...mapState([
            "es"
        ]),
        indexes (){
            return this.es.indexList
        },
        logs (){
            return this.es.logs
        },
        totalItems () {
            return this.es.logs.resp.hits.total.value
        },
        chartOptions() {
            return {
                chart: {
                    id: 'area-datetime',
                    type: 'area',
                    height: 350,
                    zoom: {
                        autoScaleYaxis: true
                    }
                },
                annotations: {
                    yaxis: [{
                        y: 30,
                        borderColor: '#999',
                        label: {
                            show: true,
                            text: 'Support',
                            style: {
                                color: "#fff",
                                background: '#00E396'
                            }
                        }
                    }],
                },
                dataLabels: {
                    enabled: false
                },
                markers: {
                    size: 0,
                    style: 'hollow',
                },
                xaxis: {
                    type: 'datetime',
                    min: this.es.logs.resp.aggregations.by_time.buckets[0].key,
                    tickAmount: 7,
                },
                tooltip: {
                    x: {
                        format: 'dd MMM yyyy'
                    }
                },
                fill: {
                    type: 'gradient',
                    gradient: {
                        shadeIntensity: 1,
                        opacityFrom: 0.7,
                        opacityTo: 0.9,
                        stops: [0, 100]
                    }
                },
            }
        },
        series() {
            let dataList = [];
            if (this.es.logs.resp.aggregations.by_time.buckets.length != 0) {
                let value = this.es.logs.resp.aggregations.by_time.buckets
                for (var i = 0; i < value.length; i++) {
                    dataList.push([value[i].key, value[i].doc_count])
                }
                return [{
                    data: dataList
                }]
            } else {
                return [{
                    data: [[]]
                }]
            }
        },
        header() {
            let header_list = []
            let hits = this.es.headers
//            console.log(JSON.stringify(hits))
            if (Object.keys(hits).length != 0) {
                for (var i in hits.resp._source) {
                    var h = {};
                    h["text"] = i;
                    h["value"] = i;
                    h["sortable"] = false;
                    if (/^\d{4}-\d{1,2}-\d{1,2}(.*)$/.test(hits.resp._source[i])){
                        h["disabled"] = true;
                        h["sortable"] = true;
                    }
                    header_list.push(h)
                }
                header_list.push({text: "_id", sortable: true, value: "_id", disabled: true})
            }
            return header_list
        },
        logData() {
            let data_list = []
            let hits = this.es.logs.resp.hits.hits
            if (hits.length != 0) {
                for (var i in hits) {
                    hits[i]._source._id = hits[i]._id
                    data_list.push(hits[i]._source)
                }
            }
            return data_list
        },
        totalNumberOfItems() {
            return this.es.logs.resp.hits.total.value
        }
    },
    mounted: function () {
        this.GetIndexList()
    },
    watch: {
        options: {
            handler (newValue, oldValue) {
                this.getlogs()
                console.log(JSON.stringify(newValue));
            },
            deep: true,
        },
        'elasticsearch.selected_index' :{
            handler (newValue, oldValue) {
                let params = {};
                params.id = newValue;
                this.GetHeader(params)
            }
        }

    }
}
</script>